package com.power.config;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.power.constant.AuthConstants;
import com.power.constant.BusinessEnum;
import com.power.constant.HttpConstants;
import com.power.model.LoginResult;
import com.power.model.Result;
import com.power.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.PrintWriter;
import java.time.Duration;
import java.util.UUID;

/**
 * @Description Security安全框架配置类
 * @Author dingchunlin
 * @Date 2024/07/10 21:12
 * @Version 1.0.0
 */
@Configuration
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置Security安全框架走自己的认证流程
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭跨站请求伪造防护
        http.csrf().disable();
        // 关闭跨域请求
        http.cors().disable();
        // 关闭Session使用策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 配置登录信息
        http.formLogin().loginProcessingUrl(AuthConstants.LOGIN_URL)
                .successHandler(authenticationSuccessHandler())
                .failureHandler(authenticationFailureHandler());
        //配置登出信息
        http.logout().logoutUrl(AuthConstants.LOGOUT_URL)
                .logoutSuccessHandler(logoutSuccessHandler());

        //要求所有请求都需要认证
        http.authorizeRequests().anyRequest().authenticated();
    }

    /**
     * 自定义登录成功处理器
     * @return
     */
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return (request, response, authentication) -> {
            // 登录成功处理逻辑
            response.setContentType(HttpConstants.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstants.UTF_8);

            // 使用uuid作为token
            String token = UUID.randomUUID().toString();

            // 从security中获取登录成功的用户对象
            String jsonString = JSONObject.toJSONString(authentication.getPrincipal());
            //将token作为key,用户信息作为value存入redis中
            stringRedisTemplate.opsForValue().set(AuthConstants.LOGIN_TOKEN_PREFIX + token, jsonString,
                    Duration.ofSeconds(AuthConstants.TOKEN_EXPIRE_TIME));

            //封装一个登录统一返回格式
            LoginResult loginResult = new LoginResult(token,AuthConstants.TOKEN_EXPIRE_TIME);

            // 登录成功返回token
            Result<LoginResult> success = Result.success(loginResult);

            //返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(success));
            writer.flush();
            writer.close();
        };
    }

    /**
     * 自定义登录失败处理器
     * @return
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            // 登录失败处理逻辑
            response.setContentType(HttpConstants.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstants.UTF_8);

            //封装一个登录失败统一返回格式
            Result<Object> result = new Result<>();
            result.setCode(BusinessEnum.OPERATION_FAIL.getCode());
            if (exception instanceof BadCredentialsException){
                result.setMsg("用户名或密码错误");
            }else if (exception instanceof UsernameNotFoundException){
                result.setMsg("用户不存在");
            }else if (exception instanceof AccountExpiredException){
                result.setMsg("账号异常，请联系管理员");
            }else if (exception instanceof AccountStatusException){
                result.setMsg("账号异常，请联系管理员");
            }else if (exception instanceof InternalAuthenticationServiceException){
                result.setMsg(exception.getMessage());
            }else {
                result.setMsg(BusinessEnum.OPERATION_FAIL.getDesc());
            }
            //返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(result));
            writer.flush();
            writer.close();
        };
    }

    /**
     * 自定义登出成功处理器
     * @return
     */
    @Bean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            // 登出成功处理逻辑
            response.setContentType(HttpConstants.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstants.UTF_8);

            //从请求头中获取token
            String authorization = response.getHeader(AuthConstants.AUTHORIZATION);
            String token = authorization.replace(AuthConstants.BEARER, "");
            //从redis中删除token
            stringRedisTemplate.delete(AuthConstants.LOGIN_TOKEN_PREFIX + token);

            //封装一个登出成功统一返回格式
            Result<Object> success = Result.success(null);

            //返回结果
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            writer.write(objectMapper.writeValueAsString(success));
            writer.flush();
            writer.close();
        };
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
